package com.hdu.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hdu.entity.Role;
import com.hdu.mapper.RoleMapper;
import com.hdu.service.IRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 权限实体类 服务实现类
 * </p>
 *
 * @author xiaobai
 * @since 2024-05-21
 */
@Service
@RequiredArgsConstructor
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {

    private final RoleMapper roleMapper;

    /**
     * 获取角色信息
     */
    @Override
    public List<Role> getRoleInfo(String roleList, String roleName) {
        QueryWrapper<Role> wrapper = new QueryWrapper<>();
        wrapper.like(!StrUtil.isEmpty(roleName), "role_name", roleName);
        List<Role> roles = list(wrapper);
        if (!"".equals(roleList)) {
            for (Role role : roles) {
                if (roleList.contains(role.getId())) {
                    role.setSelect(true);
                }
            }
        }
        return roles;
    }

    /**
     * 新增角色
     */
    @Override
    public void append(Role role) {
        String roleId = String.valueOf((int) (Math.random() * 900 + 100));
        while (getById(roleId) != null) {
            roleId = String.valueOf((int) (Math.random() * 900 + 100));
        }
        role.setId(roleId);
        roleMapper.insert(role);
    }

    /**
     * 分配菜单
     */
    @Override
    public void assign(String roleId, String[] menuId) {
        Role role = new Role();
        role.setId(roleId);
        String menuList = Arrays.asList(menuId).toString();
        role.setMenuList(menuList.substring(1, menuList.length() - 1));
        roleMapper.updateById(role);
    }
}

